﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UtilZ.Dotnet.DBIBase;

namespace UtilZ.Dotnet.DBPostgreSQL
{
    /// <summary>
    /// PostgreSQLDBAccess
    /// </summary>
    internal partial class PostgreSQLDBAccess : DBAccessAbs
    {
        /// <summary>
        /// sql语句最大长度
        /// </summary>
        private const long SQL_MAX_LENGTH = 1048576;
        public PostgreSQLDBAccess(IDBInteraction dbInteraction, DatabaseConfig config, string databaseTypeName)
            : base(dbInteraction, config, databaseTypeName, SQL_MAX_LENGTH)
        {

        }

        /// <summary>
        /// 最优化表,回收不使用的空间,并整理数据文件的碎片
        /// </summary>
        /// <param name="tableNames">表名列表,如果为null或空,则全部执行</param>
        protected override void PrimitiveOptimizeTable(List<string> tableNames)
        {
            using (var con = base.CreateConnection(DBVisitType.W))
            {
                if (tableNames == null || tableNames.Count == 0)
                {
                    List<DBTableInfo> list = this.PrimitiveGetTableInfoList(con.DbConnection, false);
                    tableNames = list.Select(t => { return t.Name; }).ToList();
                }

                foreach (var tableName in tableNames)
                {
                    string sql = $@"VACUUM FULL TABLE {tableName}";
                    base.PrimitiveExecuteNonQuery(sql, DBVisitType.W, null);
                }
            }
        }

        /// <summary>
        /// 创建数据库对象
        /// </summary>
        /// <returns></returns>
        protected override IDatabase CreateDatabase()
        {
            return new PostgreSQLDatabase(this);
        }
    }
}
